package net.pinnoocle.playdao.entity.page;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页工具类
 *
 * @author ye
 * @since 2021-09-01 15:42:37
 */
@Data
@NoArgsConstructor
@ApiModel("分页基本信息")
public class PageModel<T> implements Serializable {
  private static final long serialVersionUID = 1L;

  @ApiModelProperty("总记录数")
  private int totalCount;

  @ApiModelProperty("每页记录数")
  private int pageSize;

  @ApiModelProperty("总页数")
  private int totalPage;

  @ApiModelProperty("当前页数")
  private int curPage;

  @ApiModelProperty("列表数据")
  private List<T> list;


  /**
   * 分页 带参数构造器
   *
   * @param list 列表数据
   * @param totalCount 总记录数
   * @param pageSize 每页记录数
   * @param curPage 当前页数
   */
  public PageModel(List<T> list, int totalCount, int pageSize, int curPage) {
    this.list = list;
    this.totalCount = totalCount;
    this.pageSize = pageSize;
    this.curPage = curPage;

    this.totalPage = (int) Math.ceil((double) totalCount / pageSize);
  }

  /**
   * 分页构造器 带mybatis-plus分页参数
   *
   * @param page mybatis-plus分页参数
   */
  public PageModel(Page<T> page) {
    this.list = page.getRecords();
    this.totalCount = (int) page.getTotal();
    this.pageSize = (int) page.getSize();
    this.curPage = (int) page.getCurrent();
    this.totalPage = (int) page.getPages();
  }

  public <R> PageModel(IPage<R> page, List<T> content) {
    this.totalCount = (int) page.getTotal();
    this.pageSize = (int) page.getSize();
    this.curPage = (int) page.getCurrent();
    this.totalPage = (int) page.getPages();
    this.list = content;
  }

  private <R> PageModel(IPage<R> page, Function<R, T> converter) {
    this(page, page.getRecords().stream().map(converter).collect(Collectors.toList()));

  }

  public static <R, T> PageModel<T> from(IPage<R> page, Function<R, T> converter) {
    return new PageModel<>(page, converter);
  }

  public static <R, T> PageModel<T> from(IPage<R> page, List<T> content) {
    return new PageModel<>(page, content);
  }

  public static <R> PageModel<R> from(IPage<R> page) {
    return new PageModel<>(page, page.getRecords());
  }
}
